package com.atguigu.guli.service.trade.controller.api;

import com.atguigu.guli.common.util.StreamUtils;
import com.atguigu.guli.service.base.result.R;

import com.atguigu.guli.service.trade.entity.Order;
import com.atguigu.guli.service.trade.service.OrderService;
import com.atguigu.guli.service.trade.service.WxPayService;
import com.atguigu.guli.service.trade.util.WxPayProperties;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@RequestMapping("/api/trade/wxpay")
@RestController
public class ApiWxPayController {

    @Autowired
    WxPayService wxPayService;
    @Autowired
    OrderService orderService;
    @GetMapping("auth/create-native/{orderNo}")  //用httpclientutils创建client，通过orderNo获取order，将要的xml先用map分装起来，然后发送请求，然后把前端需要的返回值从请求返回值中和订单中获取
    public R createNative(@PathVariable String orderNo, HttpServletRequest request){
        Map map = wxPayService.createNative(orderNo, request);
        return R.ok().data(map);
    }

    @PostMapping("/notifyurl")   //微信回调的方法，先要验证签名是否正确，在通过数据流中的orderno获取数据库订单信息，对比两者的金额是否一样，最后验证是否已支付，更新订单状态，最后已支付订单的数据库新增数据
    public String  notifyurl(HttpServletRequest request){
        String returnXmlStr = wxPayService.nofityurl(request);
        return returnXmlStr;

    }

    @GetMapping("/auth/getStatus/{orderId}")  //前端通过定时任务访问的地址，返回订单状态
    public R getStatusById(@PathVariable String orderId){
        Order order = orderService.getById(orderId);
        Integer status = order.getStatus();
        return R.ok().data("status",status+"");
    }
}
